package com.limao.DBProvider;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.limao.CacheManager.CrowdUserAuthCache;
import com.limao.CacheManager.CrowdVRUserRmbCache;
import com.limao.CacheManager.user_rmbCacheManager;
import com.limao.DBDataClass.CrowdUserShopDataClass;
import com.limao.DBDataClass.UserShopBuy5Sell5;
import com.limao.DbConnection.DbConnectionManager;
import com.limao.Model.LzPluginException;
import com.limao.Model.PublicData;
import com.limao.Tool.CacheClass;
import com.limao.push.SysRmbRecTypeEnum;


public class CrowdUserShopProvider {

	private static class UserParentProviderContainer {
		private static CrowdUserShopProvider instance = new CrowdUserShopProvider();
	}

	public static CrowdUserShopProvider getInstance() {
		return UserParentProviderContainer.instance;
	}
	
	// 初始化
	private CrowdUserShopProvider() {

	}
	
	
	private CrowdUserShopDataClass encapOrderData(ResultSet rs) throws Exception{
		
		CrowdUserShopDataClass orderData = new CrowdUserShopDataClass();
	
		orderData.sellid = rs.getString("sellid");
		orderData.userid = rs.getString("userid");
		orderData.vrgoodsid = rs.getString("vrgoodsid");
		orderData.state = rs.getString("state");
		orderData.type = rs.getString("type");
		orderData.num = rs.getString("num");
		orderData.price = rs.getString("price");
		orderData.rmb = rs.getString("rmb");
		orderData.ctime = rs.getString("ctime");
		orderData.stime = rs.getString("stime");
		orderData.endtime = rs.getString("endtime");
		orderData.buyuserid = rs.getString("buyuserid");
		orderData.buytime = rs.getString("buytime");
		orderData.numed = rs.getString("numed");
		
		orderData.username = rs.getString("username");
		orderData.avatar = rs.getString("avatar");
		
		String ctimeStr=CacheClass.date2String(CacheClass.getLongValue(orderData.ctime),"yyyyMMdd");
		
		int d1=CacheClass.getProjectDays3(ctimeStr);
		int d2=CacheClass.getProjectDays3(orderData.stime);
		
		orderData.nowdays=(0-d1)+"";
		orderData.updays=(d2-d1)+"";
		
		return orderData;
	}

	
	public CrowdUserShopDataClass loadUserShopGoodsBySellid(long sellid)
	{
		CrowdUserShopDataClass tmp=null;
		Connection con = null;
	    PreparedStatement pstmt = null;
	    ResultSet rs = null;
	    try {
	       con = DbConnectionManager.getConnection();
		   pstmt = con.prepareStatement("select us.*,a.username,a.avatar from cd_user_shop us " +
		   		" inner join cd_user_auth a on a.userid=us.userid " +
		   		" where us.sellid=?"); 
	       pstmt.setLong(1, sellid);
	       rs=pstmt.executeQuery();
	       if(rs.next())
	       {
	    	   tmp=encapOrderData(rs);
	       }
	  }
	  catch (Exception e) {
	  		tmp=null;
	      e.printStackTrace();
		} finally {
			DbConnectionManager.closeConnection(rs, pstmt, con);
	  }
	   return tmp;
		
	}
	
	//发布寄售
	public boolean Create_UserShopGoods(int userid, int vrgoodsid,float num, float rmb,float price,int type) throws LzPluginException
	{
		boolean abortTransaction = false;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			Date now=new Date();
			if(type==0) //出售
			{
				con = DbConnectionManager.getTransactionConnection();
				//先扣用户瓶数
				pstmt = con.prepareStatement("update cd_user_num set num =(num -?) where userid=? and vrgoodsid=? and (num -?)>=0 ;");
				pstmt.setBigDecimal(1, CacheClass.toBigDecimal(num+""));
				pstmt.setInt(2, userid);
				pstmt.setInt(3, vrgoodsid);
				pstmt.setBigDecimal(4, CacheClass.toBigDecimal(num+""));
				if(pstmt.executeUpdate()!=1)
				{
					abortTransaction = true;
					throw new LzPluginException("现货瓶数不足。");
				}
				
				//取更新后的新值
				String manowtotalrmb="0";
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("select num from cd_user_num where userid=? and vrgoodsid=? ;");
				pstmt.setInt(1, userid);
				pstmt.setInt(2, vrgoodsid);
				rs=pstmt.executeQuery();
				if(rs.next())
				{
					manowtotalrmb=rs.getString("num");
				}
				
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("INSERT INTO cd_sys_rmb (userid,payuserid,rmb,level,type,time,name,image,nowrmb,vrgoodsid) VALUES (?,?,?,?,?,?,?,?,?,?)");
				pstmt.setInt(1, userid);
				pstmt.setInt(2, 0);
				pstmt.setBigDecimal(3, CacheClass.toBigDecimal((0-num)+""));
				pstmt.setInt(4, 0);
				pstmt.setInt(5, SysRmbRecTypeEnum.type101.getIntVlue());  //寄售中出售现货瓶数
				pstmt.setLong(6, now.getTime());
				pstmt.setString(7, "系统");
				pstmt.setString(8, "");
				pstmt.setBigDecimal(9, CacheClass.toBigDecimal(manowtotalrmb));
				pstmt.setInt(10, vrgoodsid);
				pstmt.execute();
				
				//插入寄售
				int inFoundvailDay=CacheClass.getIntValue(CacheClass.getSYS_BaseDataCacheManager().Load_Param("inFoundvailDay").trim());
				int MacreditDay=CacheClass.getIntValue(CacheClass.getSYS_BaseDataCacheManager().Load_Param("MacreditDay").trim());
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("insert into cd_user_shop (userid,vrgoodsid,state,num,price,rmb,type,time,ctime,stime,endtime) values (?,?,?,?,?,?,?,?,?,?,?);");
				pstmt.setInt(1, userid);
				pstmt.setInt(2, vrgoodsid);
				pstmt.setInt(3, 0);
				pstmt.setBigDecimal(4, CacheClass.toBigDecimal(num+""));
				pstmt.setBigDecimal(5, CacheClass.toBigDecimal(price+""));
				pstmt.setBigDecimal(6, CacheClass.toBigDecimal(rmb+""));
				pstmt.setInt(7, type);
				pstmt.setInt(8, CacheClass.getHms_int(now,"yyyyMMdd"));
				pstmt.setLong(9, now.getTime());
				pstmt.setInt(10, CacheClass.getDateAfterDay2(now, inFoundvailDay)); //
				pstmt.setInt(11, CacheClass.getDateAfterDay2(now, inFoundvailDay+MacreditDay)); //上架后3天
				pstmt.execute();
			}
			else //采购
			{
				con = DbConnectionManager.getTransactionConnection();
				//先扣用户 余额
				pstmt = con.prepareStatement("update cd_user_rmb set nowrmb =(nowrmb -?) where userid=? and (nowrmb -?)>=0");
				pstmt.setBigDecimal(1, CacheClass.toBigDecimal(rmb+""));
				pstmt.setInt(2, userid);
				pstmt.setBigDecimal(3, CacheClass.toBigDecimal(rmb+""));
				if(pstmt.executeUpdate()!=1)
				{
					abortTransaction = true;
					throw new LzPluginException("余额不足。");
				}
				
				//取更新后的新值
				String nowrmb="0";
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("select nowrmb from cd_user_rmb where userid=?");
				pstmt.setInt(1, userid);
				rs=pstmt.executeQuery();
				if(rs.next())
				{
					nowrmb=rs.getString("nowrmb");
				}
				
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("INSERT INTO cd_sys_rmb (userid,payuserid,rmb,level,type,time,name,image,nowrmb) VALUES (?,?,?,?,?,?,?,?,?)");
				pstmt.setInt(1, userid);
				pstmt.setInt(2, 0);
				pstmt.setBigDecimal(3, CacheClass.toBigDecimal((0-rmb)+""));
				pstmt.setInt(4, 0);
				pstmt.setInt(5, SysRmbRecTypeEnum.type11.getIntVlue());  //寄售中预扣采购金额  
				pstmt.setLong(6, now.getTime());
				pstmt.setString(7, "系统");
				pstmt.setString(8, "");
				pstmt.setBigDecimal(9, CacheClass.toBigDecimal(nowrmb));
				pstmt.execute();
				
				//插入寄售
				int inFoundvailDay=0;
				int MacreditDay=CacheClass.getIntValue(CacheClass.getSYS_BaseDataCacheManager().Load_Param("MacreditDay").trim());
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("insert into cd_user_shop (userid,vrgoodsid,state,num,price,rmb,type,time,ctime,stime,endtime) values (?,?,?,?,?,?,?,?,?,?,?);");
				pstmt.setInt(1, userid);
				pstmt.setInt(2, vrgoodsid);
				pstmt.setInt(3, 1);
				pstmt.setBigDecimal(4, CacheClass.toBigDecimal(num+""));
				pstmt.setBigDecimal(5, CacheClass.toBigDecimal(price+""));
				pstmt.setBigDecimal(6, CacheClass.toBigDecimal(rmb+""));
				pstmt.setInt(7, type);
				pstmt.setInt(8, CacheClass.getHms_int(now,"yyyyMMdd"));
				pstmt.setLong(9, now.getTime());
				pstmt.setInt(10, CacheClass.getDateAfterDay2(now, inFoundvailDay)); //
				pstmt.setInt(11, CacheClass.getDateAfterDay2(now, inFoundvailDay+MacreditDay)); //上架后3天
				pstmt.execute();
			}
			
			
			
			
		} catch (Exception e) {
			e.printStackTrace();
			abortTransaction=true;
			if(e instanceof LzPluginException)
			{
				throw new LzPluginException(e.getMessage());
			}
		} finally {
			DbConnectionManager.closeTransactionConnection(rs, pstmt, con, abortTransaction);
		}
		
		if(!abortTransaction)
		{
			CrowdUserAuthCache.getInstance().ClearObjectCache(userid+"");
		}
		
		return abortTransaction;
		
	}
	
	//买前5
	public List<UserShopBuy5Sell5> getUserShopGoodsListForBuy5(int vrgoodsid)
	{
		List<UserShopBuy5Sell5> list=new ArrayList<UserShopBuy5Sell5>();
		Connection con = null;
	    PreparedStatement pstmt = null;
	    ResultSet rs = null;
	    try {
	    	con = DbConnectionManager.getConnection();
	    	pstmt = con.prepareStatement("select price,sum(num) as totalnum  from cd_user_shop where vrgoodsid=? and time=? and type=0  and state<2 GROUP BY price ORDER BY price desc  LIMIT 5; ");
	    	pstmt.setInt(1, vrgoodsid);
	    	pstmt.setInt(2, CacheClass.getYMD_int());
	    	rs=pstmt.executeQuery();
	    	while(rs.next())
	    	{
	    		UserShopBuy5Sell5 tmp=new UserShopBuy5Sell5();
	    		tmp.price=rs.getString("price");
	    		tmp.totalnum=rs.getString("totalnum");
	    		list.add(tmp);
	    	}
	    }catch (Exception e) {
	    	list.clear();
		    e.printStackTrace();
		} finally {
			DbConnectionManager.closeConnection(rs, pstmt, con);
		}
	    return list;
	}
	
	//卖前5
	public List<UserShopBuy5Sell5> getUserShopGoodsListForSell5(int vrgoodsid)
	{
		List<UserShopBuy5Sell5> list=new ArrayList<UserShopBuy5Sell5>();
		Connection con = null;
	    PreparedStatement pstmt = null;
	    ResultSet rs = null;
	    try {
	    	con = DbConnectionManager.getConnection();
	    	pstmt = con.prepareStatement("select tb.* from (select price,sum(num-numed) as totalnum  from cd_user_shop where vrgoodsid=? and time=? and type=1  and state<2 GROUP BY price ORDER BY price asc  LIMIT 5) tb ORDER BY tb.price desc; ");
	    	pstmt.setInt(1, vrgoodsid);
	    	pstmt.setInt(2, CacheClass.getYMD_int());
	    	rs=pstmt.executeQuery();
	    	while(rs.next())
	    	{
	    		UserShopBuy5Sell5 tmp=new UserShopBuy5Sell5();
	    		tmp.price=rs.getString("price");
	    		tmp.totalnum=rs.getString("totalnum");
	    		list.add(tmp);
	    	}
	    }catch (Exception e) {
	    	list.clear();
		    e.printStackTrace();
		} finally {
			DbConnectionManager.closeConnection(rs, pstmt, con);
		}
	    return list;
	}	
	
	
	//
	public List<UserShopBuy5Sell5> getUserShopGoodsListFor30DaysPrice(int vrgoodsid)
	{
		List<UserShopBuy5Sell5> list=new ArrayList<UserShopBuy5Sell5>();
		Connection con = null;
	    PreparedStatement pstmt = null;
	    ResultSet rs = null;
	    try {
	    	con = DbConnectionManager.getConnection();
	    	pstmt = con.prepareStatement("select ymdid,price from cd_analy_ymdprice where vrgoodsid=? ORDER BY ymdid desc  LIMIT 30; ");
	    	pstmt.setInt(1, vrgoodsid);
	    	rs=pstmt.executeQuery();
	    	while(rs.next())
	    	{
	    		UserShopBuy5Sell5 tmp=new UserShopBuy5Sell5();
	    		tmp.price=rs.getString("price");
	    		tmp.ymd=rs.getString("ymdid");
	    		list.add(tmp);
	    	}
	    }catch (Exception e) {
	    	list.clear();
		    e.printStackTrace();
		} finally {
			DbConnectionManager.closeConnection(rs, pstmt, con);
		}
	    return list;
	}
	
	
	//取寄售列表信息
	public PublicData getUserShopGoodsList(int vrgoodsid,int type,int curpage,String keyword)
	{
		
		Connection con = null;
	    PreparedStatement pstmt = null;
	    ResultSet rs = null;
	    PublicData tmp=null;
	    ArrayList<Object> listArry= null;
	    try {
	   	
	       List<CrowdUserShopDataClass> authObjList= new ArrayList<CrowdUserShopDataClass>();
	       int  total=0;
	       con = DbConnectionManager.getConnection();
		   pstmt = con.prepareCall("{call GetUserShopGoodsList(?,?,?,?)}"); 
		   pstmt.setInt(1, vrgoodsid);
		   pstmt.setInt(2, type);
	       pstmt.setInt(3, curpage);
	       pstmt.setString(4, keyword);
	       

	       boolean hadResults=pstmt.execute();
	       int mm=0;
	       while (hadResults) {
	       	if(tmp==null) tmp=new PublicData();
	          	rs=pstmt.getResultSet();
	          	if(mm==0)
	          	{
	          		while(rs != null && rs.next())
	          		{
	          			authObjList.add(encapOrderData(rs));
	          		}
	          	}
	         	else 
	          	{
	          		while(rs != null && rs.next()){
	          			total=total+rs.getInt(1);
	          		}
	          	}
	           hadResults = pstmt.getMoreResults(); //检查是否存在更多结果集
	           mm++;
	       }
	       DbConnectionManager.closeConnection(rs, pstmt, con);	      
	       
	       if(authObjList.size()>0)
	       {
	    	   if(listArry==null) listArry=new ArrayList<Object>();
	    	   listArry.addAll(authObjList);
	       }
			
			if((total%20)>0)
			{
				total=(total/20+1);
			}
			else
				total=(total/20);
			
			if(total==0) total=1;
			tmp.total=total+"";

			

	       tmp.curpage=curpage+"";
	       tmp.list=listArry;

	  }
	  catch (Exception e) {
	  		tmp=null;
	      e.printStackTrace();
		} finally {
			DbConnectionManager.closeConnection(rs, pstmt, con);
	  }
	   return tmp;

    }
	
	
	//购买寄售
	public boolean Buy_UserShopGoods(int userid, CrowdUserShopDataClass tmp,long sellid,int type,float num) throws LzPluginException
	{
		boolean abortTransaction = false;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		int vrgoodsid=CacheClass.getIntValue(tmp.vrgoodsid);
		try {
			Date now=new Date();
			con = DbConnectionManager.getTransactionConnection();
			
			if(type==0) //该寄售是出售 ，那么本操作就为采购
			{
				//先扣购买用户金额
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("update cd_user_rmb set nowrmb =(nowrmb -?) where userid=? and (nowrmb -?)>=0");
				pstmt.setBigDecimal(1, CacheClass.toBigDecimal(tmp.rmb));
				pstmt.setInt(2, userid);
				pstmt.setBigDecimal(3, CacheClass.toBigDecimal(tmp.rmb));
				if(pstmt.executeUpdate()!=1)
				{
					abortTransaction = true;
					throw new LzPluginException("您的商城金额不足。");
				}
				//更新瓶数
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("select * from cd_user_num where userid=? and vrgoodsid=? ;");
				pstmt.setInt(1, userid);
				pstmt.setInt(2, vrgoodsid);
				rs=pstmt.executeQuery();
				if(rs.next()) //存在 则更新
				{
					DbConnectionManager.fastcloseStmt(rs,pstmt);
					pstmt = con.prepareStatement("update cd_user_num set num=(num+?) where userid=? and vrgoodsid=? ;");
					pstmt.setBigDecimal(1, CacheClass.toBigDecimal(tmp.num));
					pstmt.setInt(2, userid);
					pstmt.setInt(3, vrgoodsid);
					pstmt.executeUpdate();
					
				}
				else//不存在  则插入
				{
					DbConnectionManager.fastcloseStmt(rs,pstmt);
					pstmt = con.prepareStatement("insert into cd_user_num (userid,vrgoodsid,num) VALUES (?,?,?);");
					pstmt.setInt(1, userid);
					pstmt.setInt(2, vrgoodsid);
					pstmt.setBigDecimal(3, CacheClass.toBigDecimal(tmp.num));
					pstmt.execute();
					
				}
				
				
				
				//生成成交记录
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("INSERT INTO cd_sys_usershoplog " +
						" (selluserid,buyuserid,num,price,rmb,sellid,time,ctime,vrgoodsid)" +
						" VALUES (?,?,?,?,?,?,?,?,?)");
				pstmt.setInt(1, CacheClass.getIntValue(tmp.userid));
				pstmt.setInt(2, userid);
				pstmt.setBigDecimal(3, CacheClass.toBigDecimal(tmp.num));
				pstmt.setBigDecimal(4, CacheClass.toBigDecimal(tmp.price));
				pstmt.setBigDecimal(5, CacheClass.toBigDecimal(tmp.rmb) );
				pstmt.setLong(6, sellid);
				pstmt.setInt(7, CacheClass.getHms_int(now,"yyyyMMdd"));
				pstmt.setLong(8, now.getTime());
				pstmt.setInt(9, vrgoodsid);
				pstmt.execute();
				//取得刚成交的logid
				long logid=0;
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("select logid from  cd_sys_usershoplog where  sellid=? and ctime=? and selluserid=? and buyuserid=? ;");
				pstmt.setLong(1, sellid);
				pstmt.setLong(2, now.getTime());
				pstmt.setInt(3, CacheClass.getIntValue(tmp.userid));
				pstmt.setInt(4, userid);
				rs=pstmt.executeQuery();
				if(rs.next())
				{
					logid=rs.getLong("logid");
				}
				if(logid==0)
				{
					abortTransaction = true;
					throw new LzPluginException("出错。");
				}
				
				
				//取购买用户更新后的新值
				String manowtotalrmb="0";
				String nowrmb="0";
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("select nowrmb from cd_user_rmb where userid=?");
				pstmt.setInt(1, userid);
				rs=pstmt.executeQuery();
				if(rs.next())
				{
					nowrmb=rs.getString("nowrmb");
					
				}
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("select num from cd_user_num where userid=? and vrgoodsid=? ;");
				pstmt.setInt(1, userid);
				pstmt.setInt(2, vrgoodsid);
				rs=pstmt.executeQuery();
				if(rs.next())
				{
					manowtotalrmb=rs.getString("num");
				}
				
				
				//购买用户现货瓶数记录
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("INSERT INTO cd_sys_rmb (userid,payuserid,rmb,level,type,time,name,image,nowrmb,orderid,vrgoodsid) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
				pstmt.setInt(1, userid);
				pstmt.setInt(2, 0);
				pstmt.setBigDecimal(3, CacheClass.toBigDecimal(tmp.num));
				pstmt.setInt(4, 0);
				pstmt.setInt(5, SysRmbRecTypeEnum.type102.getIntVlue());  //寄售中购买增加现货瓶数
				pstmt.setLong(6, now.getTime());
				pstmt.setString(7, "系统");
				pstmt.setString(8, "");
				pstmt.setBigDecimal(9, CacheClass.toBigDecimal(manowtotalrmb));
				pstmt.setLong(10, logid);
				pstmt.setInt(11, vrgoodsid);
				pstmt.execute();
				
				//购买用户余额变动记录
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("INSERT INTO cd_sys_rmb (userid,payuserid,rmb,level,type,time,name,image,nowrmb,orderid) VALUES (?,?,?,?,?,?,?,?,?,?)");
				pstmt.setInt(1, userid);
				pstmt.setInt(2, 0);
				pstmt.setBigDecimal(3, CacheClass.toBigDecimal(  (0-CacheClass.getFloatValue(tmp.rmb))+"" ) );
				pstmt.setInt(4, 0);
				pstmt.setInt(5, SysRmbRecTypeEnum.type3.getIntVlue());  //寄售中购买现货瓶数减少金额
				pstmt.setLong(6, now.getTime());
				pstmt.setString(7, "系统");
				pstmt.setString(8, "");
				pstmt.setBigDecimal(9, CacheClass.toBigDecimal(nowrmb));
				pstmt.setLong(10, logid);
				pstmt.execute();
				
				//寄售状态改变
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("update cd_user_shop set state=2,buyuserid=?,buytime=? where sellid=? ;");
				pstmt.setInt(1, userid);
				pstmt.setLong(2, now.getTime());
				pstmt.setLong(3, sellid);
				pstmt.executeUpdate();
				
				//出售者 金额 更新
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("update cd_user_rmb set nowrmb =(nowrmb +?) where userid=? ;");
				pstmt.setBigDecimal(1, CacheClass.toBigDecimal(tmp.rmb));
				pstmt.setInt(2, CacheClass.getIntValue(tmp.userid));
				if(pstmt.executeUpdate()!=1)
				{
					abortTransaction = true;
					throw new LzPluginException("出售者 金额 更新 出错。");
				}
				
				//取出售者更新后的新值
				nowrmb="0";
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("select nowrmb from cd_user_rmb where userid=?");
				pstmt.setInt(1, CacheClass.getIntValue(tmp.userid));
				rs=pstmt.executeQuery();
				if(rs.next())
				{
					nowrmb=rs.getString("nowrmb");
				}
				
				//购买用户余额变动记录
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("INSERT INTO cd_sys_rmb (userid,payuserid,rmb,level,type,time,name,image,nowrmb,orderid) VALUES (?,?,?,?,?,?,?,?,?,?)");
				pstmt.setInt(1, userid);
				pstmt.setInt(2, 0);
				pstmt.setBigDecimal(3, CacheClass.toBigDecimal(tmp.rmb) );
				pstmt.setInt(4, 0);
				pstmt.setInt(5, SysRmbRecTypeEnum.type4.getIntVlue());  //寄售出售成功金额增加
				pstmt.setLong(6, now.getTime());
				pstmt.setString(7, "系统");
				pstmt.setString(8, "");
				pstmt.setBigDecimal(9, CacheClass.toBigDecimal(nowrmb));
				pstmt.setLong(10, logid);
				pstmt.execute();
			}
			else //该寄售是采购 ，那么本操作就为出售
			{
				//先更新寄售数量 或状态
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("update cd_user_shop set state=if(numed+?=num,2,1),numed=numed+? where sellid=? and numed+?<=num;");
				pstmt.setBigDecimal(1, CacheClass.toBigDecimal(num+"") );
				pstmt.setBigDecimal(2, CacheClass.toBigDecimal(num+"") );
				pstmt.setLong(3, sellid);
				pstmt.setBigDecimal(4, CacheClass.toBigDecimal(num+"") );
				if(pstmt.executeUpdate()!=1)
				{
					abortTransaction = true;
					throw new LzPluginException("数量太多了， 出错。");
				}
				
				//出售者 增加金额
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("update cd_user_rmb set nowrmb=(nowrmb+?) where userid=? ;");
				pstmt.setBigDecimal(1, CacheClass.Bmul_D(num+"", tmp.price));
				pstmt.setInt(2, userid);
				pstmt.executeUpdate();
				
				//出售者  减少瓶数数量
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("update cd_user_num set num=(num-?),num15days=(num15days-?) where userid=? and vrgoodsid=? and (num-?)>=0 and (num15days-?)>=0;");
				pstmt.setBigDecimal(1, CacheClass.toBigDecimal(num+""));
				pstmt.setBigDecimal(2, CacheClass.toBigDecimal(num+""));
				pstmt.setInt(3, userid);
				pstmt.setInt(4, vrgoodsid);
				pstmt.setBigDecimal(5, CacheClass.toBigDecimal(num+""));
				pstmt.setBigDecimal(6, CacheClass.toBigDecimal(num+""));
				if(pstmt.executeUpdate()!=1)
				{
					throw new LzPluginException("出错，瓶数不足。");
				}
				
				
				//生成成交记录
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("INSERT INTO cd_sys_usershoplog " +
						" (selluserid,buyuserid,num,price,rmb,sellid,time,ctime,vrgoodsid)" +
						" VALUES (?,?,?,?,?,?,?,?,?)");
				pstmt.setInt(1, userid);
				pstmt.setInt(2, CacheClass.getIntValue(tmp.userid));
				pstmt.setBigDecimal(3, CacheClass.toBigDecimal(num+""));
				pstmt.setBigDecimal(4, CacheClass.toBigDecimal(tmp.price));
				pstmt.setBigDecimal(5, CacheClass.Bmul_D(num+"", tmp.price) );
				pstmt.setLong(6, sellid);
				pstmt.setInt(7, CacheClass.getHms_int(now,"yyyyMMdd"));
				pstmt.setLong(8, now.getTime());
				pstmt.setInt(9, vrgoodsid);
				pstmt.execute();
				//取得刚成交的logid
				long logid=0;
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("select logid from  cd_sys_usershoplog where  sellid=? and ctime=? and selluserid=? and buyuserid=? ;");
				pstmt.setLong(1, sellid);
				pstmt.setLong(2, now.getTime());
				pstmt.setInt(3, userid);
				pstmt.setInt(4, CacheClass.getIntValue(tmp.userid));
				rs=pstmt.executeQuery();
				if(rs.next())
				{
					logid=rs.getLong("logid");
				}
				if(logid==0)
				{
					abortTransaction = true;
					throw new LzPluginException("出错。");
				}
				
				
				
				//采购者 瓶数 更新
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("select * from cd_user_num where userid=? and vrgoodsid=? ;");
				pstmt.setInt(1, CacheClass.getIntValue(tmp.userid));
				pstmt.setInt(2, vrgoodsid);
				rs=pstmt.executeQuery();
				if(rs.next()) //存在 则更新
				{
					DbConnectionManager.fastcloseStmt(rs,pstmt);
					pstmt = con.prepareStatement("update cd_user_num set num=(num+?) where userid=? and vrgoodsid=? ;");
					pstmt.setBigDecimal(1, CacheClass.toBigDecimal(num+""));
					pstmt.setInt(2, CacheClass.getIntValue(tmp.userid));
					pstmt.setInt(3, vrgoodsid);
					pstmt.executeUpdate();
					
				}
				else//不存在  则插入
				{
					DbConnectionManager.fastcloseStmt(rs,pstmt);
					pstmt = con.prepareStatement("insert into cd_user_num (userid,vrgoodsid,num) VALUES (?,?,?);");
					pstmt.setInt(1, CacheClass.getIntValue(tmp.userid));
					pstmt.setInt(2, vrgoodsid);
					pstmt.setBigDecimal(3, CacheClass.toBigDecimal(num+""));
					pstmt.execute();
					
				}

				//取出 采购者 更新后的新值
				//取更新后的新值
				String manowtotalrmb="0";
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("select num from cd_user_num where userid=? and vrgoodsid=? ;");
				pstmt.setInt(1, CacheClass.getIntValue(tmp.userid));
				pstmt.setInt(2, vrgoodsid);
				rs=pstmt.executeQuery();
				if(rs.next())
				{
					manowtotalrmb=rs.getString("num");
				}
				//采购者 瓶数变动记录
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("INSERT INTO cd_sys_rmb (userid,payuserid,rmb,level,type,time,name,image,nowrmb,orderid,vrgoodsid) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
				pstmt.setInt(1, CacheClass.getIntValue(tmp.userid));
				pstmt.setInt(2, 0);
				pstmt.setBigDecimal(3, CacheClass.toBigDecimal(num+"") );
				pstmt.setInt(4, 0);
				pstmt.setInt(5, SysRmbRecTypeEnum.type107.getIntVlue());  //寄售中采购 成交得瓶数
				pstmt.setLong(6, now.getTime());
				pstmt.setString(7, "系统");
				pstmt.setString(8, "");
				pstmt.setBigDecimal(9, CacheClass.toBigDecimal(manowtotalrmb));
				pstmt.setLong(10, logid);
				pstmt.setInt(11, vrgoodsid);
				pstmt.execute();
				
				
				
				//取出 出售者 更新后的新值
				String manowtotalrmb1="0";
				String nowrmb="0";
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("select nowrmb from cd_user_rmb where userid=?");
				pstmt.setInt(1, userid);
				rs=pstmt.executeQuery();
				if(rs.next())
				{
					nowrmb=rs.getString("nowrmb");
				}
				
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("select num from cd_user_num where userid=? and vrgoodsid=? ;");
				pstmt.setInt(1, userid);
				pstmt.setInt(2, vrgoodsid);
				rs=pstmt.executeQuery();
				if(rs.next())
				{
					manowtotalrmb1=rs.getString("num");
				}
				
				
				//出售者余额变动记录
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("INSERT INTO cd_sys_rmb (userid,payuserid,rmb,level,type,time,name,image,nowrmb,orderid) VALUES (?,?,?,?,?,?,?,?,?,?)");
				pstmt.setInt(1, userid);
				pstmt.setInt(2, 0);
				pstmt.setBigDecimal(3, CacheClass.Bmul_D(num+"", tmp.price) );
				pstmt.setInt(4, 0);
				pstmt.setInt(5, SysRmbRecTypeEnum.type4.getIntVlue());  
				pstmt.setLong(6, now.getTime());
				pstmt.setString(7, "系统");
				pstmt.setString(8, "");
				pstmt.setBigDecimal(9, CacheClass.toBigDecimal(nowrmb));
				pstmt.setLong(10, logid);
				pstmt.execute();
				//出售者瓶数变动记录
				DbConnectionManager.fastcloseStmt(rs,pstmt);
				pstmt = con.prepareStatement("INSERT INTO cd_sys_rmb (userid,payuserid,rmb,level,type,time,name,image,nowrmb,vrgoodsid) VALUES (?,?,?,?,?,?,?,?,?,?)");
				pstmt.setInt(1, userid);
				pstmt.setInt(2, 0);
				pstmt.setBigDecimal(3, CacheClass.toBigDecimal((0-num)+"") );
				pstmt.setInt(4, 0);
				pstmt.setInt(5, SysRmbRecTypeEnum.type101.getIntVlue()); 
				pstmt.setLong(6, now.getTime());
				pstmt.setString(7, "系统");
				pstmt.setString(8, "");
				pstmt.setBigDecimal(9, CacheClass.toBigDecimal(manowtotalrmb1));
				pstmt.setLong(10, vrgoodsid);
				pstmt.execute();
				
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
			abortTransaction=true;
			if(e instanceof LzPluginException)
			{
				throw new LzPluginException(e.getMessage());
			}
		} finally {
			DbConnectionManager.closeTransactionConnection(rs, pstmt, con, abortTransaction);
		}
		
		if(!abortTransaction)
		{
			CrowdUserAuthCache.getInstance().ClearObjectCache(userid+"");
			if(tmp!=null)
				CrowdUserAuthCache.getInstance().ClearObjectCache(tmp.userid);
		}
		
		return abortTransaction;
		
	}
		
	
	//转入瓶数申请
	public boolean Create_IN_Trade(int userid,int vrgoodsid, int num) throws LzPluginException
	{
		boolean abortTransaction = false;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			Date now=new Date();
			con = DbConnectionManager.getTransactionConnection();
			//先扣用户瓶数
			pstmt = con.prepareStatement("update cd_user_num set num=(num-?) where userid=? and vrgoodsid=? and (num -?)>=0 ;");
			pstmt.setBigDecimal(1, CacheClass.toBigDecimal(num+""));
			pstmt.setInt(2, userid);
			pstmt.setInt(3, vrgoodsid);
			pstmt.setBigDecimal(4, CacheClass.toBigDecimal(num+""));
			if(pstmt.executeUpdate()!=1)
			{
				abortTransaction = true;
				throw new LzPluginException("现货瓶数不足。");
			}
			
			//取更新后的新值
			String manowtotalrmb="0";
			DbConnectionManager.fastcloseStmt(rs,pstmt);
			pstmt = con.prepareStatement("select num from cd_user_num where userid=? and vrgoodsid=? ;");
			pstmt.setInt(1, userid);
			pstmt.setInt(2, vrgoodsid);
			rs=pstmt.executeQuery();
			if(rs.next())
			{
				manowtotalrmb=rs.getString("num");
			}
			
			DbConnectionManager.fastcloseStmt(rs,pstmt);
			pstmt = con.prepareStatement("INSERT INTO cd_sys_rmb (userid,payuserid,rmb,level,type,time,name,image,nowrmb,vrgoodsid) VALUES (?,?,?,?,?,?,?,?,?,?)");
			pstmt.setInt(1, userid);
			pstmt.setInt(2, 0);
			pstmt.setBigDecimal(3, CacheClass.toBigDecimal((0-num)+""));
			pstmt.setInt(4, 0);
			pstmt.setInt(5, SysRmbRecTypeEnum.type104.getIntVlue());  
			pstmt.setLong(6, now.getTime());
			pstmt.setString(7, "系统");
			pstmt.setString(8, "");
			pstmt.setBigDecimal(9, CacheClass.toBigDecimal(manowtotalrmb));
			pstmt.setInt(10, vrgoodsid);
			pstmt.execute();
			
			//插入 预转入订单
			DbConnectionManager.fastcloseStmt(rs,pstmt);
			pstmt = con.prepareStatement("insert into cdvr_sys_num (userid,vrgoodsid,num,state,time,ctime) values (?,?,?,?,?,?);");
			pstmt.setInt(1, userid);
			pstmt.setInt(2, vrgoodsid);
			pstmt.setInt(3, num);
			pstmt.setInt(4, 0);
			pstmt.setInt(5, CacheClass.getHms_int(now,"yyyyMMdd"));
			pstmt.setLong(6, now.getTime());
			pstmt.execute();
			
		} catch (Exception e) {
			e.printStackTrace();
			abortTransaction=true;
			if(e instanceof LzPluginException)
			{
				throw new LzPluginException(e.getMessage());
			}
		} finally {
			DbConnectionManager.closeTransactionConnection(rs, pstmt, con, abortTransaction);
		}
		
		if(!abortTransaction)
		{
			CrowdUserAuthCache.getInstance().ClearObjectCache(userid+"");
			user_rmbCacheManager.getInstance().ClearObjectCache(userid+"");
			CrowdVRUserRmbCache.getInstance().ClearObjectCache(userid+"");
		}
		
		return abortTransaction;
		
	}
	
	
}
